#include "communication.h"

//******SPI******
void spi_master_init(void)
{
	//SS MOSI SCK are output
	DDRB |= _BV(PB2) | _BV(PB3) | _BV(PB5);
	//Enable Master SPI
	SPCR = _BV(SPE) | _BV(MSTR);
	//Double SPI with no prescale = 1/2 Fosc
	SPSR = _BV(SPI2X);
}

void spi_off(void)
{
	SPCR = 0;
}

uint8_t spi_tx(uint8_t data)
{
	//Put the data in the buffer
	SPDR = data;
	//Wait until the transfer is complete
	loop_until_bit_is_set(SPSR, SPIF);
	//Read the data received
	return SPDR;
}

void ss_hi(void)
{
	PORTB |= _BV(PB2);
}

void ss_lo(void)
{
	PORTB &= ~_BV(PB2);
}

//******UART******
void uart_9600(void)
{
	#undef BAUD
	#define BAUD 38400
	#include <util/setbaud.h>
	UBRR0H = UBRRH_VALUE;
	UBRR0L = UBRRL_VALUE;

	#if USE_2X
	UCSR0A |= (1 << U2X0);
	#else
	UCSR0A &= ~(1 << U2X0);
	#endif

	UCSR0B = _BV(RXEN0) | _BV(TXEN0);
}

void uart_tx(uint8_t data)
{
	loop_until_bit_is_set(UCSR0A, UDRE0);
	UDR0 = data;
}

uint8_t uart_rx(void)
{
	loop_until_bit_is_set(UCSR0A, RXC0);
	return(UDR0);
}
